<template>
	<view class="box-bg">
		<uni-nav-bar shadow color="#F7F7F7" left-icon="left" backgroundColor="#3485FD" height="65px" title="专业洗车"
			@clickLeft="back" />
	</view>
	<view class="main1">
		<uni-search-bar class="search-bar" bgColor="#fff" @confirm="handleSearch" radius="100" placeholder="请输入需要搜索的内容"
			cancelButton="none" @clear="clear" :focus="true" v-model="searchValue"></uni-search-bar>
		<view v-if="searchHistory?.length > 0" class="lishijilu-view">
			<view class="lishijilu-wrap">
				<view class="lishijilu">历史记录：</view>
				<view class="clear-history" @click="clearHistory">🗑️清空历史</view>
			</view>
			<view class="lishijilu-keywords">
				<view v-for="(keyword, index) in searchHistory" :key="index" class="lishijilu-name"
					@click="handleHistoryClick(keyword)">
					{{ keyword }}
				</view>
			</view>
		</view>
	</view>
	<view class="main2">
		<uni-card v-for="(item, index) in filteredStoreList" :key="index" class="main2-card">
			<view class="main2-view">
				<view class="main2-view-name">{{ item.name }}</view>
				<view class="main2-view-distance">{{ item.distance }}km</view>
			</view>
			<view class="main2-view-num">
				<view class="main2-view-rate">
					<uni-rate allow-half :value="item.rate / 2" size="15" />
					{{ item.rate }}分
				</view>
				<view class="main2-view-number">销量: {{ item.sales }}</view>
			</view>
			<view class="main2-view-open">
				<image class="main2-view-img" :src="item.imgUrl" mode="aspectFill" v-if="item.imgUrl"></image>
				<view class="main2-view-opentime">
					<view class="main2-view-date">营业时间：周一至周五</view>
					<view class="main2-view-time">早上{{ item.startTime.split(' ')[1] }}-晚上{{ item.endTime.split(' ')[1]
					}}</view>
					<view class="main2-view-address">{{ item.operatingArea + item.address }}</view>
				</view>
			</view>
		</uni-card>
		<view style="margin-left: 39%;width: 22%; padding-left: 14rpx;">--暂无更多--</view>
	</view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import baseUrl from '@/untils/urlConfig';
import unirequest from '@/untils/unirequest';
// 新增：获取用户当前位置（需要定位权限）
const getUserLocation = async () => {
	try {
		const { latitude, longitude } = await uni.getLocation({
			type: 'wgs84',
			altitude: true
		});
		return { userLat: latitude, userLng: longitude };
	} catch (error) {
		uni.showToast({
			title: '获取位置失败，请开启定位权限',
			icon: 'none'
		});
		return null;
	}
};
// 响应式数据
const searchValue = ref('');
const searchHistory = ref([]);  // 搜索历史记录
const filteredStoreList = ref([]);  // 搜索结果列表（原storeList改为原始数据）
const originalStoreList = ref([]);
// 新增：Haversine公式计算经纬度距离（单位：Km）
const getDistance = (lat1, lng1, lat2, lng2) => {
	const R = 6371; // 地球半径（Km）
	const dLat = (lat2 - lat1) * Math.PI / 180;
	const dLng = (lng2 - lng1) * Math.PI / 180;
	const a =
		Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
		Math.sin(dLng / 2) * Math.sin(dLng / 2);
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	return parseFloat((R * c).toFixed(2)); // 保留两位小数
};

const getStoreList = async () => {
	try {
		uni.showLoading({ title: '加载中...' });
		// 先获取用户位置
		const userLocation = await getUserLocation();
		if (!userLocation){
			uni.hideLoading();   
			return;
		}
		const res = await unirequest({
			url: `${baseUrl}/chy/merchant/list`,
			method: 'GET'
		});
		if (!res?.data) {  // 增加空值校验
            throw new Error('接口响应格式错误');
        }
		if (res.data.code === 200) {
			originalStoreList.value = res.data.rows.map(store =>
			({
				id: store.id,
				name: store.name,
				operatingArea: store.operatingArea,
				longitude: store.longitude,
				latitude: store.latitude,
				rate: store.rate,
				sales: store.sales,
				imgUrl: store.imgUrl,
				startTime: store.startTime,
				endTime: store.endTime,
				address: store.address,
				// 新增：计算并格式化距离（保留2位小数）
				distance: getDistance(
					userLocation.userLat,
					userLocation.userLng,
					store.latitude,
					store.longitude
				)
			}));
			filteredStoreList.value = originalStoreList.value;  // 初始显示全部数据
		} else {
			uni.showToast({
				title: '获取门店列表失败:' + (res.data.msg || '无错误信息'), 
				icon: 'none'
			});
		}
		const response = await unirequest({
			url: `${baseUrl}/chy/tupian/list`,
			method: 'GET'
		});
		if (!response?.data) {  // 增加空值校验
            throw new Error('图片接口响应格式错误');
        }
		if (response.data.code === 200) {
			// 处理图片数据，确保每个门店都有图片
			originalStoreList.value.forEach(store => {
				// 查找匹配的图片并直接更新门店的 imgUrl 属性
				const foundImg = response.data.rows.find(img => img.mid === store.id);
				if (foundImg) {
					store.imgUrl = foundImg.img; // 图片的 URL 属性名为 img，根据实际情况修改
				}
				else {
					store.imgUrl = '/static/liuying.jpg';
				}
			})
		}
		else {
			uni.showToast({
				title: '获取图片列表失败:' + (response.data.msg || '无错误信息'), 
				icon: 'none'
			});
		}
		const resp = await unirequest({
			url: `${baseUrl}/chy/servicedetails/list`,
			method: 'GET'
		});
		if (!resp?.data) {  // 增加空值校验
            throw new Error('服务详情接口响应格式错误');
        }
		if (resp.data.code === 200) {
			const salesMap = {};
			resp.data.rows.forEach(detail => {
				const mId = detail.mId;
				salesMap[mId] = (salesMap[mId] || 0) + 1; // 相同mId计数+1
			});

			// 将统计结果赋值给对应商家的sales字段
			originalStoreList.value.forEach(store => {
				store.sales = salesMap[store.id] || 0; // 无匹配时销量为0
			});
			// 更新搜索结果列表（确保新销量生效）
			filteredStoreList.value = [...originalStoreList.value];
		}
		else {
			uni.showToast({
				title: '获取服务详情列表失败:' + (resp.data.msg || '无错误信息'), icon: 'none'
			});
		}
		uni.hideLoading();  // 加载完成后隐藏
	} catch (error) {
		uni.hideLoading();  // 加载失败也要隐藏
		console.error('完整错误堆栈:', error);
		uni.showToast({
			title: '获取门店列表失败' + (error.message || '未知错误'),
			icon: 'none'
		})
	}
};
onMounted(() => {
	const history = uni.getStorageSync('washcarSearchHistory') || [];
	searchHistory.value = history;
	getStoreList();
});
// 监听搜索词变化（实时搜索）
watch(searchValue, (newVal) => {
	if (newVal) {
		// 防抖处理（500ms内无输入才触发搜索）
		clearTimeout(window.searchTimer);
		window.searchTimer = setTimeout(() => {
			handleSearch(newVal);
		}, 500);
	} else {
		// 输入为空时显示全部数据
		filteredStoreList.value = originalStoreList.value;
	}
});
// 搜索处理函数
const handleSearch = (keyword) => {
	// 添加历史记录（去重+限制最多10条）
	if (!searchHistory.value.includes(keyword)) {
		searchHistory.value.unshift(keyword);  // 添加到数组头部
		if (searchHistory.value.length > 10) searchHistory.value.pop();  // 保留最近10条
		uni.setStorageSync('washcarSearchHistory', searchHistory.value);  // 持久化存储
	}
	searchValue.value = keyword;
	uni.showLoading({ title: '搜索中...', mask: true, duration: 300 });
	// 过滤数据（假设从原始数据过滤，实际可根据接口实现）
	filteredStoreList.value = originalStoreList.value.filter(store =>
		store.name.includes(keyword)
	);
	if (filteredStoreList.value.length === 0) {
		uni.showToast({
			title: '未找到相关门店',
			icon: 'none'
		});
	}
	uni.hideLoading();
};

// 点击历史记录回填搜索框
const handleHistoryClick = (keyword) => {
	searchValue.value = keyword;
	handleSearch(keyword);  // 立即搜索
};
// 清空历史记录
const clearHistory = () => {
	searchHistory.value = [];
	uni.removeStorageSync('washcarSearchHistory'); // 清空本地存储
	filteredStoreList.value = originalStoreList.value; // 恢复全部数据
};

// 返回方法
const back = () => {
	uni.navigateBack();
};

// 清空搜索内容（可选，若原代码有逻辑可补充）
const clear = () => {
	searchValue.value = '';
};

</script>

<style>
.box-bg {
	position: fixed;
	width: 100%;
	top: 0;
	z-index: 1000;
}

.main1 {
	background-color: #1168EA;
	padding: 25rpx;
	padding-bottom: 140rpx;
	margin-top: 115rpx;
}

.lishijilu-view {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
	position: relative;
	top: 25rpx;
	margin-bottom: 25rpx;
}

.lishijilu-wrap {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.lishijilu-keywords {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;
	margin-top: 20rpx;
	overflow: hidden;
	max-height: 100rpx;
}

.lishijilu {
	font-size: 30rpx;
	margin: auto;
	color: white;
	position: absolute;
	left: 25rpx;
}

.clear-history {
	font-size: 20rpx;
	color: #ffffff80;
	cursor: pointer;
	position: absolute;
	right: 25rpx;
	margin-top: 6rpx;
}

.lishijilu-name {
	font-size: 25rpx;
	margin: 0;
	padding: 4rpx 15rpx; /* 上下5rpx，左右15rpx内边距 */
	color: white;
	background-color: rgba(255, 255, 255, 0.2); /* 半透明白色背景 */
	border-radius: 20rpx;
	white-space: nowrap; /* 防止关键词换行 */
}

.main2-view,
.main2-view-num,
.main2-view-rate,
.main2-view-open {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 10rpx 0 10rpx 0;
}

.main2-view-opentime {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	height: 140rpx;
}

.main2-view-num {
	width: 60%;
}

.main2-view-rate {
	width: 50%;
}

.main2-view-img {
	width: 45%;
	height: 180rpx;
	border-radius: 25rpx
}

.main2-view-name {
	font-size: 35rpx;
	color: #000;
}

.main2-view-distance {
	color: #0060FD;
}

.main2-view-date,
.main2-view-time,
.main2-view-address {
	font-size: 25rpx;
	color: #000;
}

.main2-view-rate,
.main2-view-number {
	color: #000;
}

.main2 {
	position: relative;
	top: -140rpx;
}
</style>